//
//  HMUserInformation.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/21.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

class HMUserInformation: HMTableViewController {
    // 静态数据
    var dataAry: Array<Any>! // 模板格式
    private var hmUser =  HMLoginParam.share.user // 获取登陆的本地信息
    private var maskView: UIView? // 遮罩
    private var selectIndexPath: IndexPath?
    private var headImg: String = ""
    private var oldHeadImg: String = ""
    // 配置
    override func load() {
        self.title = "用户信息"
        self.tableView.register(HMUserCell.classForCoder(), forCellReuseIdentifier: "HMUserCell")
        //禁止滑动
        self.tableView.isScrollEnabled = false

        let _imgUrl = configure.shareConfigure.IP_diagonal + (hmUser["iconUrl"] as! String)
        let _name = (hmUser["nickname"] as! String)
        let _sex = (hmUser["sex"] as! Int) == 1 ? "男" : "女"
        let h =  hmUser["height"] as! Int
        let w = hmUser["weight"] as! Int
        
        self.dataAry = [["icon": _imgUrl, "title": "头像:"],
                        ["title": "昵称:", "describe": _name, "hiddenImg": true],
                        ["title": "性别:", "describe": _sex],
        ["title": "身高:", "describe": "\(h) cm"],
        ["title": "体重:", "describe": "\(w) kg"],]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        super.hideHeader()
        super.hideFooter()
        self.addRBtn()
    }
    
    /// 添加导航栏右 按钮
    func addRBtn() {
        let but = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 38))
        but.setTitle("保存设置", for: .normal)
        but.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        but.addTarget(self, action: #selector(save), for: UIControlEvents.touchUpInside)
        let itemR = UIBarButtonItem.init(customView: but)
        self.navigationItem.rightBarButtonItem = itemR
    }
    @objc func save(sender: UIButton) {
        
        HMUtils.share.showHUD("正在提交中...")
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.request(url: "user/icon", parameters: ["iconUrl" : headImg], success: { (json) in
//              self.hmUser["iconUrl"]  = json["data"]["iconUrl"].stringValue
        }, fail: { (error, msg) in

        }, complete: {
            
            
            let dic: [String : Any] = ["sex": self.hmUser["sex"]!, "height":self.hmUser["height"]!,"weight":self.hmUser["weight"]!, "liveMode": 1, "sportMode": 1]
            NetRequestTool.requestForJSON(url: "user/base-info", parameters: dic, success: { (json) in
                 HMUtils.share.hideHUD()
                 HMLoginParam.updateUser(self.hmUser)
                 self.navigationController?.popViewController(animated: true)
            }, fail: { (error, msg) in
                // print("-------->", msg)
                HMUtils.share.hideHUD()
            }) {}
        })
        
        

        
        
    }
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return self.dataAry.count
    }
    // cell 数据
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            let newcell = cell as! HMUserCell
            let newDic = self.dataAry[indexPath.row] as! NSDictionary
            let jsonData = newDic.mj_JSONData()
            let js = try? JSON.init(data: jsonData!)
        newcell.setJson(json: js!)
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row  == 0 {
            return 100
        }else {
            return 50
        }
    }
    override func cellForRow(atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "HMUserCell") as! HMUserCell
        return cell
        
    }
    override  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.selectIndexPath = indexPath
        if indexPath.row == 0 {
           oldHeadImg = self.hmUser["iconUrl"] as! String
           HMPhoto.shareInstance.pushTZImagePickerController(self, max: 1, column: 1, isSelectOriginal: true)
            HMPhoto.shareInstance.hmImagePickerVc?.didFinishPickingPhotosHandle = {
                (photos, assets, isSelectOriginalPhoto) -> () in
                
              let imgs  = HMPhoto.requestHeadImages(photos: photos!, assets: assets!)
                
                NetRequestTool.shareInstance.met = .post
                NetRequestTool.upload(url: "/user/image/upload", data: imgs.datas, imgName: imgs.imgAssets as! [String] ,parameters: [:], success: { (json) in
                    self.headImg = json["url"].stringValue
                    let _imgUrl = configure.shareConfigure.IP_diagonal + json["url"].stringValue
                    let newcell = self.tableView.cellForRow(at: indexPath) as! HMUserCell
                    newcell.icon.img(url: _imgUrl)
                    self.hmUser["iconUrl"] = self.headImg
                }) { (err, msg) in
                    print("HMUserInformation-->>", err, msg)
                }
                
            }
        }else {
            if indexPath.row != 1 {
                var ary1 = Array<Any>()
                if indexPath.row == 2 {
                    ary1 = ["男", "女"]
                }else if indexPath.row == 3 {
                    for  i in 150..<190 {
                        ary1.append("\(i) cm")
                    }
                }else if indexPath.row == 4{
                    for  i in 30..<129 {
                        ary1.append("\(i) kg")
                    }
                }
                HMPickerView.sharePicker.delegate = self
                HMPickerView.sharePicker.sign = "\(indexPath.row)"
                HMPickerView.creator(nil, picker: ["Ary" : ary1])
            }else {
                //初始化UITextField
                var inputText = UITextField()
                let msgAlertCtr = UIAlertController.init(title: nil, message: "请输入用户昵称", preferredStyle: .alert)
                let ok = UIAlertAction.init(title: "确定", style:.default) { (action:UIAlertAction) ->() in
                    if((inputText.text) == ""){
//                        print("你输入的是：\(String(describing: inputText.text))")
                        self.hmUser["nickname"] = inputText.text
                       
                    }
                }
                
                let cancel = UIAlertAction.init(title: "取消", style:.cancel) { (action:UIAlertAction) -> ()in  }
                msgAlertCtr.addAction(ok)
                msgAlertCtr.addAction(cancel)
                //添加textField输入框
                msgAlertCtr.addTextField { (textField) in
                    //设置传入的textField为初始化UITextField
                    inputText = textField
                    inputText.placeholder = "请输入用户昵称"
                }
                //设置到当前视图
                self.present(msgAlertCtr, animated: true, completion: nil)
            }
        }
        
        
        
    }
    
    @objc func onMask(sender: UITapGestureRecognizer) {
        HMPickerView.hidePickeView()
        maskView?.removeFromSuperview()
    }
    
    
}

extension HMUserInformation: HMPickerViewDelegate {
    func cancel() {
//         maskView?.removeFromSuperview()
    }
    
    func selectValue(sign: String, value: String, row: Int, component: Int) {
        let indexPath = self.selectIndexPath!
        let newcell = self.tableView.cellForRow(at: indexPath) as! HMUserCell
        newcell.describe.text = value
    
        if (sign == "2") {
            if value == "男" {
                hmUser["sex"] = 1
            }else {
                hmUser["sex"] = 2
            }
        }else if (sign == "3"){
            
            let h = Int(value.prefix(value.count - 3))
             hmUser["height"] = h
        }else {
            let w = Int(value.prefix(value.count - 3))
             hmUser["weight"] = w
        }
        
        
    }
    
 
}
